import { RootState } from '@/types/store'
import { Input, NavBar, TextArea } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'

import styles from './index.module.scss'

type Props={
    closehandle:()=>void,
    type: '' | 'name' | 'intro',
    update:(type:string,value:string)=>void
}
const EditInput = ({closehandle,type,update}:Props) => {
    const {userProfile} = useSelector((state:RootState)=>state.Profile)
    const [value,setValue] = useState(
        type==='name'?userProfile.name:userProfile.intro
    )
    const iptRef=useRef<InputRef>(null)
    const textAreaRef=useRef<TextAreaRef>(null)
    useEffect(()=>{
        if(type==='name'){
            iptRef.current?.focus()
        }else{
            textAreaRef.current?.focus()
            document.querySelector('textarea')?.setSelectionRange(-1,-1)
        }
    },[type])
    
  return (
    <div className={styles.root}>
      <NavBar className="navbar" right={<span onClick={()=>update(type,value)} className="commit-btn">提交</span>} onBack={closehandle}>
        编辑{type==='name' ?'昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{type==='name' ?'昵称' : '简介'}</h3>

        {type === 'name' ? (
          <div className="input-wrap">
            <Input placeholder="请输入昵称"  value={value} ref={iptRef} onChange={(e)=>setValue(e)}/>
          </div>
        ) : (
          <TextArea
            className="textarea"
            placeholder="请输入简介"
            showCount
            maxLength={99}
            value={value}
            ref={textAreaRef}
            onChange={(e)=>setValue(e)}
          />
        )}
      </div>
    </div>
  )
}

export default EditInput